import { getToken, setToken, removeToken } from '@/plugins/utils/auth'
import { asyncRoutes, constantRoutes } from '@/router'
import axios from 'axios'

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    // debugger
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  token: getToken(),
  routes: [],
  addRoutes: []
}

const mutations = {
  SAVE_TOKEN: (state, token) => {
    setToken(token)
  },
  RESET_TOKEN: (state, info) => {
    state.token = ''
    state.routes = []
    removeToken()
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_USERINFO: (state, info) => {
    state.userInfo = info
  },
  GET_USER_PERMISSION: (state, routes) => {
    console.log('%c [ routes ]-58', 'font-size:13px; background:pink; color:#bf2c9f;', routes)

  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('superAdmin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  // 登出登录
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      commit('RESET_TOKEN')
      location.reload()// 为了重新实例化vue-router对象 避免bug
      resolve()
    })
  }

}

export default {
  state,
  mutations,
  actions
}
